﻿#region Licence
// <copyright file="Core/SysGroupeViewModel.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Core.Class;
using Core.Enums;
using Database.POCO;
using GalaSoft.MvvmLight.CommandWpf;
using Helpers;
using Helpers.Class;
using Interfaces.Enums;

#endregion

namespace Core.ViewModel.Controls
{
    /// <summary>
    /// 
    /// </summary>
    public class SysGroupeViewModel : ViewModelBaseModule
    {
        #region properties

        /// <summary>
        /// 
        /// </summary>
        private SysGroupe _groupe;
        public SysGroupe Groupe
        {
            get { return _groupe; }
            set
            {
                _groupe = value;
                RaisePropertyChanged(() => Groupe);
            }
        }

        public ObservableCollection<UserInclude> UsersIncludeInGroupes { get; set; }

        /// <summary>
        /// 
        /// </summary>
        private ObservableCollection<UserInclude> _usersReferent;
        public ObservableCollection<UserInclude> UsersReferent
        {
            get { return _usersReferent; }
            set
            {
                _usersReferent = value;
                RaisePropertyChanged(() => UsersReferent);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private List<RightsParameter> _droitsGroupe;
        public List<RightsParameter> DroitsGroupe
        {
            get { return _droitsGroupe; }
            set
            {
                _droitsGroupe = value;
                RaisePropertyChanged(() => DroitsGroupe);
            }
        }
        public RelayCommand CloseCommand { get; set; }
        public RelayCommand SaveCommand { get; set; }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="groupe"></param>
        public SysGroupeViewModel(SysGroupe groupe)
        {
            Groupe = groupe;
            UsersIncludeInGroupes = new ObservableCollection<UserInclude>();
            UsersIncludeInGroupes.CollectionChanged += UsersIncludeInGroupesOnCollectionChanged;

            UsersReferent = new ObservableCollection<UserInclude>();

            LoadUsersForGroupe();
            LoadUsersReferent();

            LoadRights();

            SaveCommand = new RelayCommand(Save, CanSave);
            CloseCommand = new RelayCommand(Close);
        }

        /// <summary>
        /// 
        /// </summary>
        public SysGroupeViewModel() : this(new SysGroupe())
        {}

        #region RelayCommand

        private void Save()
        {
            Groupe.Utilisateurs = UsersIncludeInGroupes.Where(u => u.IsChecked).Select(u => u.Utilisateur).ToList();
            Services.DatabaseService.Service.Save<SysGroupe>(Groupe);

            //1.Gestion des référents
            Services.DatabaseService.Service.Delete<SysReferentGroupe>(r => r.Groupe.ID == Groupe.ID, true);
            var referents = UsersReferent.Where(u => u.IsChecked).Select(u => u.Utilisateur).ToList();
            foreach (var utilisateur in referents)
            {
                Services.DatabaseService.Service.Save<SysReferentGroupe>(new SysReferentGroupe
                {
                    Groupe = Groupe,
                    Referent = utilisateur
                });
            }

            //2. On supprime tous les droits du groupe
            Services.DatabaseService.Service.Delete<SysUtilisateurDroitFonction>(d => d.Groupe.ID == Groupe.ID);

            //3. Enregistrement des droits du groupe
            foreach (var rightsParameter in DroitsGroupe)
            {
                foreach (var droitFonction in rightsParameter.Droits)
                {
                    if (droitFonction.ValueTemp != 0)
                    {
                        droitFonction.DroitFonction.Value = droitFonction.ValueTemp;
                        Services.DatabaseService.Service.Save<SysUtilisateurDroitFonction>(droitFonction.DroitFonction);
                    }
                }
            }

            CallBackConfirmed();
            CloseAction();
        }

        private bool CanSave()
        {
            return !string.IsNullOrEmpty(Groupe.Code);
        }

        private void Close()
        {
            CloseAction();
        }

        #endregion

        #region private

        private void LoadUsersForGroupe()
        {
            //Tout d'abord la liste de tous les utilisateurs
            var users = Services.DatabaseService.Service.Where<SysUtilisateur>(u => u.IsAdministrateur).OrderBy(a => a.Nom);
            foreach (var user in users)
            {
                var userAdd = new UserInclude { Utilisateur = user, IsChecked = Groupe.Utilisateurs != null && Groupe.Utilisateurs.Contains(user)}; 
                UsersIncludeInGroupes.Add(userAdd);
                if (userAdd.IsChecked)
                {
                    UsersReferent.Add(new UserInclude { Utilisateur = userAdd.Utilisateur, IsChecked = false});
                }
            }
        }

        private void LoadUsersReferent()
        {
            //Tout d'abord la liste de tous les utilisateurs
            var users = Services.DatabaseService.Service.Where<SysReferentGroupe>(r => r.Groupe.ID == Groupe.ID).OrderBy(a => a.Referent.Nom);
            foreach (var user in UsersReferent)
            {
                UserInclude user1 = user;
                var usersFound = users.Where(u => u.Referent.ID == user1.Utilisateur.ID);
                user.IsChecked = usersFound.Any();
            }
        }

        /// <summary>
        /// Chargement des droits
        /// </summary>
        private void LoadRights()
        {
            if (Services.AccessControlService.IsAuthorizedFunction(Services.RightsService.GetIdentifiantRight((int)RightsEnum.ViewParametersSystem, TypeModulesEnum.Core)))
            {
                DroitsGroupe = new List<RightsParameter>();
                var droits = Services.DatabaseService.Service.GetAll<SysDroits>().ToList();

                //On charge les droits actuels de l'utilisateur
                var userRights = Services.DatabaseService.Service.Where<SysUtilisateurDroitFonction>(d => d.Groupe.ID == Groupe.ID);

                if (droits.Any())
                {
                    foreach (var paramsGroup in droits.GroupBy(p => p.Module))
                    {
                        var newDroit = new RightsParameter
                        {
                            Header = ModulesHelper.LocalizeModule((TypeModulesEnum)paramsGroup.Key),
                            Droits = new List<RightsValue>()
                        };

                        foreach (var droit in paramsGroup)
                        {
                            var valeurDroit = 0;
                            if (userRights.Any())
                            {
                                SysDroits droit1 = droit;
                                var rights = userRights.Where(d => d.Droit.ID == droit1.ID);
                                if (rights.Any())
                                {
                                    valeurDroit = rights.First().Value;
                                }
                            }
                            newDroit.Droits.Add(new RightsValue { Droit = droit, DroitFonction = new SysUtilisateurDroitFonction { Value = 0, Groupe = Groupe, Droit = droit }, ValueTemp = valeurDroit});
                            newDroit.Droits = newDroit.Droits.OrderBy(d => d.Droit.LibelleDroit).ToList();
                        }
                        DroitsGroupe.Add(newDroit);
                    }
                }
            }
        }
        #endregion

        #region event

        private void UsersIncludeInGroupesOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                foreach (UserInclude user in e.NewItems)
                {
                    user.PropertyChanged += UserPropertyChanged;
                }
            }

            if (e.OldItems != null)
            {
                foreach (UserInclude item in e.OldItems)
                {
                    item.PropertyChanged -= UserPropertyChanged;
                }
            }
        }

        private void UserPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            //Juste pour la sélection ou non d'un User
            if (e.PropertyName == "IsChecked")
            {
                if (((UserInclude)sender).IsChecked)
                {
                    UsersReferent.Add(new UserInclude { Utilisateur = ((UserInclude)sender).Utilisateur, IsChecked = false });
                }
                else
                {
                    var items = UsersReferent.Where(u => u.Utilisateur == ((UserInclude)sender).Utilisateur);
                    foreach (var item in items)
                    {
                        UsersReferent.Remove(item);
                    }
                }
            }
        }
        #endregion
    }
}
